﻿#include "upload_file_manager.h"
#include <QNetworkAccessManager>
#include <QFile>
#include <QHttpPart>
#include <QFileInfo>
#include <QNetworkReply>
UploadFileManager::UploadFileManager(QObject *parent)
    : QObject(parent)
    ,  manager(new QNetworkAccessManager(this))
{

}

void UploadFileManager::UploadFile(QString url, QString filePath)
{
    QFile *file = new QFile(filePath);
    if(!file->open(QIODevice::ReadOnly)){
        return;
    }

    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    QHttpPart filePart;
    filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\"; filename=\"" + QFileInfo(*file).fileName() + "\""));
    filePart.setBodyDevice(file);
    QNetworkRequest request((QUrl(url)));
    filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/octet-stream"));
    multiPart->append(filePart);
    QNetworkReply *reply = manager->post(request, multiPart);
    connect(reply, &QNetworkReply::uploadProgress,this, [&](qint64 bytesSent, qint64 bytesTotal){
        qInfo()<<"bytesSent:"<<bytesSent<<",bytesTotal:"<<bytesTotal;
        if(bytesTotal !=0 )
        emit sigUploadProgress((bytesSent*1.0/bytesTotal)*100);
    });
    connect(manager, &QNetworkAccessManager::finished, this, &UploadFileManager::slotUploadFinished);
}

void UploadFileManager::slotUploadFinished(QNetworkReply *reply)
{
    if(reply)
    emit sigFinish(reply->error());
    reply->deleteLater();
}
